
import time
from homeassistant.components.sensor import SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_NAME
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from .const import DOMAIN, DEFAULT_NAME, VERSION
from .todoist_api import TodoistAPI

async def async_setup_entry(
    hass: HomeAssistant,
    entry: ConfigEntry,
    async_add_entities: AddEntitiesCallback,
) -> None:
    config = entry.data
    api = TodoistAPI(hass, config.get('token'))
    await hass.async_add_executor_job(api.init_project)
    hass.data['todoist-api'] = api
    # 添加服务
    if hass.services.has_service(DOMAIN, 'add') == False:
        # 添加
        def add_item(call):
            data = call.data
            date = data.get('date', '')
            event = data.get('event', '')
            if date != '' and event != '':
                try:
                    api.add_item(event, date)
                    hass.services.call('homeassistant', 'update_entity', { 'entity_id': 'sensor.dai_ban_shi_xiang' })
                except Exception as ex:
                    print(ex)
                    hass.services.call('persistent_notification', 'create', {"message": str(ex), "title": "待办事项", "notification_id": "todoist"})
        # 删除
        def delete_item(call):
            data = call.data
            event = data.get('event', '')
            if event != '':
                item_id = api.delete_item(event)
                if item_id is not None:
                    # 移除当前实体
                    hass.states.remove(f'input_datetime.todoist_{item_id}')
                    hass.services.call('homeassistant', 'update_entity', { 'entity_id': 'sensor.dai_ban_shi_xiang' })

        hass.services.async_register(DOMAIN, 'add', add_item)
        hass.services.async_register(DOMAIN, 'delete', delete_item)
    async_add_entities([TodoistSensor(hass, api)], True)

class TodoistSensor(SensorEntity):

    _attr_unique_id = DOMAIN

    def __init__(self, hass, api) -> None:
        self._attr_name = DEFAULT_NAME
        self.hass = hass
        self.api = api

    @property
    def device_info(self):
        return {
            "identifiers": { (DOMAIN, 'shaonianzhentan') },
            "name": DEFAULT_NAME,
            "manufacturer": 'shaonianzhentan',
            "model": 'Todoist',
            "sw_version": VERSION
        }

    async def async_update(self) -> None:
        api = self.api
        items = await self.hass.async_add_executor_job(api.get_items)
        items_len = len(items)
        if items_len == 0:
            return
        # 当前时间
        today_dt = time.localtime(time.time())
        today_date = time.strftime("%Y-%m-%d %H:%M:%S", today_dt)
        # 最近提醒时间
        latest_date = None
        latest_dt = None
        latest_content = None
        attributes = { 'update_at': today_date }
        for item in items:
            id = item['id']
            content = item['content']
            if item['due'] is None:
                dt = today_dt
                date = today_date
            else:
                date = item['due']['date'].replace('T', ' ')
                dt = time.strptime(date, '%Y-%m-%d %H:%M:%S')
                # 取大于当前时间的最小值
                if date > today_date:
                    if latest_date is None or latest_date > date:
                        latest_date = date
                        latest_dt = dt
                        latest_content = content
            '''
            # 更新对象
            entity_id = f'input_datetime.todoist_{id}'
            state = self.hass.states.get(entity_id)
            if state is None or state.state != date:
                self.set_input_datetime(f'input_datetime.todoist_{id}', "mdi:format-list-numbered", content, date, dt)
            '''
            # 设置属性
            attributes[date] = content
        # 设置状态值
        self._attr_native_value = items_len
        self._attr_native_unit_of_measurement = '项'
        self._attr_extra_state_attributes = attributes
        # 提醒时间
        entity_id = 'input_datetime.latest_time_todoist'
        state = self.hass.states.get(entity_id)
        if state is None or state.state != latest_date:
            if latest_date is None:                
                latest_date = f'2222-11-11 11:11:11'
                latest_dt = time.strptime(latest_date, '%Y-%m-%d %H:%M:%S')
                latest_content = '待办提醒时间'
            self.set_input_datetime(entity_id, "mdi:alarm", latest_content, latest_date, latest_dt)

    # 创建日期时间实体
    def set_input_datetime(self, entity_id, icon, name, state, dt):
        self.hass.states.async_set(entity_id, state, {
                "icon": icon,
                "friendly_name": name,
                'has_date': True,
                'has_time': True,
                'editable': True,
                'year': dt.tm_year,
                'month': dt.tm_mon,
                'day': dt.tm_mday,
                'hour': dt.tm_hour,
                'minute': dt.tm_min,
                'second': dt.tm_sec,
                'timestamp': int(time.mktime(dt))
            })